<template>
  <a-modal
    v-model:visible="visible"
    :title="formData && formData.id ? '修改用户' :'新增用户'"
    draggable
    :width="width"
    @cancel="handleCancel"
  >
    <a-form :model="formData" ref="formRef" auto-label-width>
      <a-spin :loading="loading">
        <a-row>
          <a-col :span="12">
            <a-form-item
              label="帐号"
              field="username"
              :rules="[{required:true,message:'帐号不能为空'}]"
              :validate-trigger="['blur']"
            >
              <a-input v-model="formData.username" placeholder="请输入用户名" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="12" v-if="!formData.id">
            <a-form-item
              label="密码"
              field="password"
              :rules="[{required:true,message:'密码不能为空'}]"
              :validate-trigger="['blur']"
            >
              <a-input-password
                v-model:visibility="visibility"
                v-model="formData.password"
                placeholder="请输入密码，不填默认为123456"
                :defaultVisibility="false"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="姓名"
              field="name"
              :rules="[{required:true,message:'姓名不能为空'}]"
              :validate-trigger="['blur']"
            >
              <a-input v-model="formData.name" placeholder="请输入姓名" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="昵称" field="nickName">
              <a-input v-model="formData.nickName" placeholder="请输入昵称" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="手机号"
              field="tel"
              :rules="[{required:true,message:'手机号不能为空'}]"
              :validate-trigger="['blur']"
            >
              <a-input
                v-model="formData.tel"
                placeholder="请输入手机号"
                :max-length="11"
                show-word-limit
                allow-clear
              />
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item
              label="性别"
              field="gender"
              :rules="[{required:true,message:'性别不能为空'}]"
              :validate-trigger="['blur']"
            >
              <a-radio-group v-model="formData.gender">
                <a-radio :value="1">男</a-radio>
                <a-radio :value="0">女</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="用户状态"
              field="status"
              :rules="[{required:true, message:'用户状态不能为空'}]"
              :validate-trigger="['blur']"
            >
              <a-switch
                type="round"
                v-model="formData.status"
                :checked-value="1"
                :unchecked-value="0"
              >
                <template #checked>{{ $t('searchTable.operation.enabled') }}</template>
                <template #unchecked>{{ $t('searchTable.operation.disabled') }}</template>
              </a-switch>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="邮箱" field="email">
              <a-input v-model="formData.email" placeholder="请输入邮箱" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="所属部门" field="deptIds">
              <a-tree-select
                allow-clear
                :data="deptData"
                v-model="formData.deptIds"
                tree-checkable
                :tree-check-strictly="true"
                :field-names="{key:'id',title:'name'}"
                placeholder="请选择所属部门"
              ></a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="所属角色" field="roleIds">
              <a-select
                v-model="formData.roleIds"
                placeholder="请选择所属角色"
                allow-search
                multiple
                :filter-option="filterOption"
                allow-clear
              >
                <a-option
                  v-for="item in roleData"
                  :key="item.value"
                  :value="item.value"
                >{{ item.label }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="所属岗位" field="postIds">
              <a-select
                v-model="formData.postIds"
                placeholder="请选择所属岗位"
                allow-search
                multiple
                :filter-option="filterOption"
                allow-clear
              >
                <a-option
                  v-for="item in postData"
                  :key="item.value"
                  :value="item.value"
                >{{ item.label }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-spin>
    </a-form>
    <template #footer>
      <a-button
        style="margin-right: 8px"
        @click="handleCancel"
      >{{ $t('searchTable.columns.operations.close') }}</a-button>
      <a-button
        type="primary"
        @click="handleSubmit"
        :loading="loading"
      >{{ $t('searchTable.columns.operations.save') }}</a-button>
    </template>
  </a-modal>
</template>
<script setup lang="ts">
import { ref, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import { Modal, Message } from '@arco-design/web-vue';

import {
  getSysUser,
  saveSysUser,
  updateSysUser,
  UserData,
} from '@/api/sys/user';
import { treeDept } from '@/api/sys/dept';
import { selectRole, selectPost, SelectData } from '@/api/common';
import { filterOption } from '@/utils/common';

const { t } = useI18n();

const loading = ref(false);
const visible = ref(false);
const width = ref('calc(38%)');
const changed = ref(false);

// 触发父组件事件 刷新用户列表
const emit = defineEmits({ onSearch: null });

// 表单
const formRef = ref<any>();
const formData = ref<UserData>({});

// 密码加密
const visibility = ref(true);
// 角色数据/部门数据
const roleData = ref<SelectData[] | undefined>([]);
const deptData = ref<any>([]);
const postData = ref<SelectData[]>([]);

// 打开弹窗
const onOpen = async (record: any) => {

  await featchRoleData();
  await featchDeptData();
  await featchPostData();
  if (record) {
    await featchUserData(record.id);
  } else {
    formData.value = {
      gender: 1,
      password: '123456',
    };
  }
  nextTick(() => {
    changed.value = false;
    visible.value = true;
  });
};

// 确认
const handleSubmit = async () => {
  formRef.value.validate().then((result: any) => {
    // 校验不通过
    if (result) {
      return;
    }
    loading.value = true;
    if (formData.value.id) {
      delete formData.value.password;
      updateSysUser(formData.value)
        .then(() => {
          onOk();
        })
        .finally(() => {
          loading.value = false;
        });
    } else {
      saveSysUser(formData.value)
        .then(() => {
          onOk();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
};

// 确认
const onOk = () => {
  formRef.value.clearValidate();
  formData.value = {};
  visible.value = false;
  Message.success(t('operations.success'));
  emit('onSearch');
};

// 取消
const handleCancel = () => {
  if (!changed.value) {
    onCancel();
  } else {
    Modal.confirm({
      title: t('operations.cancel.title'),
      content: '',
      onOk() {
        onCancel();
      },
      onCancel() {
        visible.value = true;
      },
    });
  }
};

// 取消
const onCancel = () => {
  formRef.value.clearValidate();
  formData.value = {};
  visible.value = false;
};

// 获取用户数据
const featchUserData = async (id: any) => {
  getSysUser(id).then((res) => {
    formData.value = res.data;
  });
};

// 获取角色数据
const featchRoleData = async () => {
  selectRole({ status: 1 }).then((res) => {
    roleData.value = res.data;
  });
};

// 获取部门数据
const featchDeptData = async () => {
  treeDept({}).then((res: any) => {
    deptData.value = res.data;
  });
};

// 获取岗位数据
const featchPostData = async () => {
  selectPost({}).then((res: any) => {
    postData.value = res.data;
  });
};

// 抛出函数
defineExpose({
  onOpen,
});
// 监听数据变化
watch(
  formData,
  (newValue, oldValue) => {
    changed.value = true;
  },
  { deep: true }
);
</script>
<style scoped lang="less">
</style>